import { request, catchException } from '@/util/request'
import store from '@/store/store'

async function appAuth() {
  const providerRes = (await uni.getProvider({ service: 'oauth' })) as any
  const provider = providerRes.provider?.[0] as Auth.TProvider
  const codeRes = (await uni.login({ provider, scopes: 'auth_user', onlyAuthorize: true })) as any
  const code = codeRes.code as string

  uni.hideLoading()
  let objToken
  switch (provider) {
    case 'weixin': {
      objToken = await getWXToken(code)
      break
    }
    default: {
      break
    }
  }
  const pages = getCurrentPages() //获取页面列表
  const perpage = pages[pages.length - 1] //当前页
  perpage.onLoad()
  return objToken
}
async function getWXToken(code: string) {
  const { userState } = store
  const confirm = (await uni.showModal({
    title: '授权确认',
    showCancel: true,
    cancelText: '取消',
    confirmText: '授权',
    content: '申请获取您的头像昵称',
  })) as any
  if (confirm.cancel) {
    uni.navigateBack()
    return
  }
  const userInfo = (await uni.getUserProfile({ desc: '申请获取您的头像昵称' })) as any
  const { avatarUrl: head_img, nickName: nickname } = userInfo.userInfo
  const invite = userState.inviteCode
  try {
    const res = await request({
      url: 'wechat/auth/appletIndex',
      method: 'GET',
      data: { code, nickname, head_img },
      notToken: true,
    })
    const { token, qr_code, account } = res.data.content
    const userToken = JSON.stringify({ token, qr_code })
    userState.account = account
    userState.head_img = head_img
    userState.nickname = nickname
    userState.userToken = { token, qr_code }
    uni.setStorageSync('account', account)
    uni.setStorageSync('userToken_zh_web', userToken)
    return { token, qr_code }
  } catch (error) {
    catchException(error)
  }
}

export { appAuth }
